<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Setting extends Model
{
    use HasFactory;
    protected $table = 'setting';
    protected $primaryKey = 'key';
    protected $keyType = 'string';
    public $timestamps = false;

    const MIN_URL = 'https://api.weixin.qq.com/sns/jscode2session';

    static function modifyEnv(array $data)
    {
        $envPath = base_path('.env');
        $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
        $contentArray->transform(function ($item) use ($data){
            foreach ($data as $key => $value){
                if(str_contains($item, $key)){
                    return $key . '=' . $value;
                }
            }
            return $item;
        });
        $content = implode( "\n",$contentArray->toArray());
        $res = file_put_contents($envPath, $content);
        if($res===false){
            return false;
        }else{
            return true;
        }
    }

    static function inputToData($input)
    {
        $data = [];
        foreach ($input as $k=>$v){
            $data[]=['key'=>$k,'value'=>$v,];
        }
        return $data;
    }

    static function dataToInput(array $data,array $arr)
    {
        if(!empty($data)){
            $input = [];
            foreach ($data as $v){
                $input[$v['key']]=$v['value'];
            }
            return $input;
        }else{
            $input = [];
            foreach ($arr as $v){
                $input[$v]='';
            }
            return $input;
        }
    }

    static public function updateBatch(string $tableName,  array $multipleData)
    {
        try {
            if(!$tableName || !$multipleData){
                return false;
            }
            $firstRow = current($multipleData);
            $updateColumn = array_keys($firstRow);
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            $prefix = config('database.connections.mysql.prefix');
            $prefix = $prefix?$prefix:'';
            $updateSql = "UPDATE " . $prefix.$tableName . " SET ";
            $sets = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            //Log::info($updateSql);
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }

    static function op($request,$getarr,$res,string $temp,string $route){
        if($request->isMethod('post')) {
            $data = $request->only($getarr);
            $data = self::inputToData($data);
            $insert = $request->only('insert','');
            if($insert){
                DB::table('setting')->insert($data);
            }else{
                $res = self::updateBatch('setting',$data);
            }
            if($res){
                //Cache::put('config', $siteconfig->value);
                return redirect()->route($route)->with('status', 'success');
            }else{
                return back()->with('status', 'fail');
            }
        }else{
            $siteconfig = Setting::whereIn('key',$getarr)->get()->toArray();
            $res['siteconfig'] = self::dataToInput($siteconfig,$getarr);
            return view($temp,['res'=>$res,'siteconfig'=>$siteconfig]);
        }
    }

    static function getCache(){
        Global $_G;
        $data = self::get()->toArray();
        $res = [];
        foreach ($data as $k=>$v){
            $res[$v['key']] = $v['value'];
        }
        $_G['cache'] = $res;
        return $res;
    }

}
